# coding=utf-8
import json
from abc import ABCMeta

import tornado.web

import WrapCursor
from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.Normal import Normal


class ModNormalNameHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            CheckJsonKeys(ojson, "normalID", "name")
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error(u'请求数据错误' + str(e)))
            return

        s = Session()
        normalID = ojson['normalID']
        newName = ojson['name']
        if newName is None or newName == "" or newName == u"":
            self.write((r.Error(u'名字不能为空')))
            return
        nc = s.query(Normal).filter_by(id=normalID).all()
        if len(nc) is not 1:
            self.write(r.Error(u'模式不存在'))
            return
        nc[0].name = newName
        try:
            s.commit()
        except Exception as e:
            self.write(r.Error(str(u'失败:增加模式动作失败')))
            return
        self.write(r.Ok(u'成功'))
        return
